import React, {useEffect, useState} from "react";
import {Button, DatePicker, Form, Image, Input, message, Modal, Select, Space, Table, Tooltip} from 'antd';
import {SearchOutlined, SyncOutlined, WarningOutlined,} from '@ant-design/icons';
import TenantModal from "./component/tenantModal";
import classNames from "classnames";
import {useTranslation} from 'react-i18next';
import {apiInterceptors, deleteTenantById, getLogo, getTenantList, updateTenant as updateTenantById} from '@/client/api';
import useSetTableScroll from "../../hooks/use-table-scroll";
import dayjs from 'dayjs';

const { confirm } = Modal;

const User = () => {
  const [queryForm] = Form.useForm();
  const { t } = useTranslation();

  const [handleType, setHandleType] = useState('add')
  const [isModalOpen, setIsModalOpen] = useState(false)
  const tableHeight = useSetTableScroll()
  let [tableData, setTableData] = useState([]);
  let [tenantId, setTenantId] = useState('')
  let [pagination, setPagination] = useState({
    total: 0,
    page_num: 1,
    page_size: 10
  })

  const dictStatus = [
    { dictValue: '1', dictLabel: '启用' },
    { dictValue: '0', dictLabel: '禁用' },
  ]
  const statusHandle = async (record, type) => {
    confirm({
      title: t('Tips'),
      icon: <WarningOutlined />,
      content: `你确定${record.status === '1' ? '禁用' : '启用'}该用户吗?`,
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      async onOk () {
        const [err] = await apiInterceptors(updateTenantById({ status: type, id: record.id }))
        if (!err) {
          message.success('操作成功')
          searchQueryFn()
        } else {
          return
        }
      },
    });

  }
  const columns = [
    {
      title: '租户LOGO',
      dataIndex: 'logo',
      key: 'logo',
      render: (_: any, record: any) => {
        return record.logo ? <Image src={record.src}
                     style={{marginLeft: '10px'}} height={50} width={'auto'}/> : <span/>
      }
    },
    {
      title: '租户名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '域名',
      dataIndex: 'domain',
      key: 'domain',
    },
    {
      title: 'App支持数',
      dataIndex: 'app_num',
      key: 'app_num',
    },
    {
      title: '租户管理员',
      dataIndex: 'admin_names',
      key: 'admin_names',
      render: (_:any, record: any) => {
        // return record.admin_names.toString()
        const nameStr = record.admin_names.toString()
        return (
          <Tooltip title={nameStr}>
            <span>{nameStr}</span>
          </Tooltip>
        )
      }
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      showOverflowTooltip: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (_:any, record:any) => {
        return record.status === '1' ? '启用' : '禁用'
      }
    },
    {
      title: '操作',
      render: (_:any, record:any) => (
        <Space size="middle">
          <a onClick={() => updateTenant(record)}>修改</a>
          {/*<a onClick={() => deleteTenant(record)}>删除</a>*/}
          {
            record.status === '0' ?
              <a onClick={() => statusHandle(record, '1')}>启用</a>
              :
              <a onClick={() => statusHandle(record, '0')}>禁用</a>
          }
        </Space>
      )
    }
  ]


  function searchQueryFn() {
    setPagination({ ...pagination, page_num: 1 })
    getTableList()
  }
  const paginationChange = (page: number, size:number) => {
    setPagination({
      total: pagination.total,
      page_num: page,
      page_size: size
    })
  }
  const getTableList = async () => {
    const queryData = queryForm.getFieldsValue()
    const param = {
      ...pagination,
      ...queryData,
    }
    delete param.total
    if (param.create_time){
      param.create_time = dayjs(param.create_time).unix()
    }
    const [_, data] = await apiInterceptors(getTenantList(param))

    for (const item of data?.data) {
      let name = ''
      if (item.logo) {
        let temArr = item.logo.split('/')
        name = temArr[temArr.length - 1]
        const result = await getLogo(item.id, name)
        item.src = URL.createObjectURL(result.data)
      }
    }
    setTableData(data?.data)
    setPagination({
      total: data?.total,
      page_size: pagination.page_size,
      page_num: data?.page
    })
  }
  function resetQueryFn() {
    queryForm.resetFields()
    getTableList()
  }
  function setModal(e: boolean) {
    setIsModalOpen(e)
  }
  const createHandle = () => {
    setModal(true)
    setHandleType('add')
  }
  const updateTenant = (data:any) => {
    setTenantId(data.id)
    setModal(true)
    setHandleType('edit')
  }
  const deleteTenant = (data:any) => {
    confirm({
      title: t('Tips'),
      icon: <WarningOutlined />,
      content: `你确定删除该租户吗?`,
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      async onOk () {
        const [err] = await apiInterceptors(deleteTenantById(data.id))
        if (!err) {
          message.success('删除成功')
          searchQueryFn()
        }
      },
    });
  }
  useEffect(() => {
    getTableList()
  }, [pagination.page_size, pagination.page_num])
  return (
    <div className="p-5 marvel_table_container">
      <div className="top_search p-5 bg-white dark:bg-[#232734]">
        <Form form={queryForm} layout="inline" name={'query'} autoComplete="off" className='cus_form' initialValues={{status: '1'}}>
          {/*<Space wrap={true}>*/}
          <Form.Item label="租户ID" name="id">
            <Input style={{ width: 240 }} placeholder="请输入租户名称" allowClear onPressEnter={searchQueryFn} />
          </Form.Item>
          <Form.Item label="租户名称" name="name">
            <Input style={{ width: 240 }} placeholder="请输入租户名称" allowClear onPressEnter={searchQueryFn} />
          </Form.Item>
          <Form.Item label="租户管理员" name="admin_names">
            <Input style={{ width: 240 }} placeholder="请输入租户管理员" allowClear onPressEnter={searchQueryFn} />
          </Form.Item>
          <Form.Item label="创建时间" name="create_time">
            <DatePicker
              showTime={{ format: 'HH:mm' }}
              format="YYYY-MM-DD HH:mm"
              style={{ width:  240 }}
            />
          </Form.Item>
           {/*<Form.Item label="域名" name="domain">*/}
           {/*   <Input style={{ width: 240 }} placeholder="请输入域名" allowClear onPressEnter={searchQueryFn} />*/}
           {/* </Form.Item>*/}
           {/* <Form.Item label="联系人姓名" name="contact">*/}
           {/*   <Input style={{ width: 240 }} placeholder="请输入联系人姓名" allowClear onPressEnter={searchQueryFn} />*/}
           {/* </Form.Item>*/}
           {/* <Form.Item label="联系电话" name="phone">*/}
           {/*   <Input style={{ width: 240 }} placeholder="请输入联系电话" allowClear onPressEnter={searchQueryFn} />*/}
           {/* </Form.Item>*/}
            <Form.Item name="status" label="状态">
              <Select
                style={{ width: 240 }}
                placeholder="用户状态"
                allowClear
                onChange={searchQueryFn}
                options={dictStatus.map((item) => ({
                  value: item.dictValue,
                  label: item.dictLabel,
                }))}
              />
            </Form.Item>
            <Form.Item>
              <Button onClick={searchQueryFn} type="primary" icon={<SearchOutlined />}>
                搜索
              </Button>
            </Form.Item>
            <Form.Item>
              <Button onClick={resetQueryFn} icon={<SyncOutlined />}>
                重置
              </Button>
            </Form.Item>
          {/*</Space>*/}
        </Form>
      </div>
      <Button type="primary" style={{marginTop: '20px'}} onClick={() => createHandle()}>创建租户</Button>
      <div className="user_table" style={{marginTop: '20px'}}>
        <Table
          columns={columns}
          dataSource={tableData}
          scroll={{y: tableHeight}}
          pagination={{
            total: pagination.total,
            showTotal: (total, range) => `共 ${total} 条`,
            onChange: paginationChange
          }}
          // expandable={{
          //   expandIcon: ({ expanded, onExpand, record }) =>
          //     expanded ? (
          //        <DownOutlined onClick={e => onExpand(record, e)}/>
          //     ) : (
          //       record.children ?
          //       <RightOutlined onClick={e => onExpand(record, e)} /> : ''
          //     )
          // }}
        />
      </div>
      {
        isModalOpen &&
        <TenantModal tenantId={tenantId} handleType={handleType} isModalOpen={isModalOpen} setModal={ setModal } successCall={searchQueryFn}/>
      }
    </div>
  )
}

export default User
